import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/auto_router.dart';
import 'package:casdon/common/widget/common_video_player.dart';
import 'package:casdon/common/widget/fullscreen_loading_overlay.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/modules/feedback/ui/components/feedback_media_preview.dart';
import 'package:casdon/modules/lifeCircle/data/api/life_subject_list_api.dart';
import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:casdon/modules/me/application/notification/image_picker_notifier.dart';
import 'package:casdon/modules/me/application/notification/oss_sts_notifier.dart';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:video_player/video_player.dart';

/// 生活圈发帖页面
@RoutePage()
class LifeCreatePostScreen extends ConsumerStatefulWidget {
  const LifeCreatePostScreen({super.key});

  @override
  ConsumerState<LifeCreatePostScreen> createState() =>
      _LifeCreatePostScreenState();
}

class _LifeCreatePostScreenState extends ConsumerState<LifeCreatePostScreen> {
  final TextEditingController _contentController = TextEditingController();
  final List<File> _selectedImages = [];
  final List<File> _selectedVideos = [];
  Set<String> _selectedCategoryIds = <String>{};
  bool get _hasAnyMedia =>
      _selectedImages.isNotEmpty || _selectedVideos.isNotEmpty;
  bool get _canSubmit =>
      _hasAnyMedia || _contentController.text.trim().isNotEmpty;
  bool _isSubmitting = false;
  bool _isUploading = false; // 资源上传中（显示进度条卡片）
  int _uploadTotal = 0; // 需要上传的总数
  int _uploadedCount = 0; // 已完成数
  double _currentProgress = 0.0; // 当前文件进度 0~1

  // 分类选项（接口获取）
  List<ResponseLifeSubjectApi> _subjects = [];

  @override
  void initState() {
    super.initState();
    _contentController.addListener(_handleContentChanged);
    _selectedCategoryIds = <String>{}; // 确保每次进入页面时分类为空
    _loadSubjects();
  }

  Future<void> _loadSubjects() async {
    try {
      final usecase = ref.read(lifeSujectListUsecaseProvider);
      final ret = await usecase.execute(type: 0);
      setState(() {
        _subjects = ret;
        _selectedCategoryIds = <String>{}; // 用户需手动选择分类
      });
    } catch (_) {}
  }

  @override
  void dispose() {
    _contentController.removeListener(_handleContentChanged);
    _contentController.dispose();
    super.dispose();
  }

  void _handleContentChanged() {
    if (!mounted) {
      return;
    }
    setState(() {});
  }

  /// 选择图片/视频
  Future<void> _pickMedia() async {
    final notifier = ref.read(imagePickerNotifierProvider.notifier);

    // 判断是否已选择视频：如果已选择视频，不能再选择图片；如果已选择图片，不能再选择视频
    final bool hasVideo = _selectedVideos.isNotEmpty;
    final bool hasImages = _selectedImages.isNotEmpty;

    ImagePickerConfig config;
    if (hasVideo) {
      // 已选择视频，禁止再选择其他类型
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('只能选择一个视频或9张图片')));
      }
      return;
    } else if (hasImages) {
      // 已选择图片，禁止再选择视频，仅允许继续选择图片
      if (_selectedImages.length >= 9) {
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('最多只能选择9张图片')));
        }
        return;
      }
      // 仅图片，最多选择9张
      config = ImagePickerConfig(
        pickerType: PickerType.imageOnly,
        maxImages: 9 - _selectedImages.length,
      );
    } else {
      // 未选择任何媒体，可以选择图片或视频（最多9张图片或1个视频）
      config = const ImagePickerConfig(
        pickerType: PickerType.imageAndVideo,
        maxImages: 9,
        maxVideos: 1,
      );
    }

    final result = await notifier.pickFromGallery(
      context: context,
      config: config,
    );

    if (result != null && result.hasData && mounted) {
      // 如果一个选择会话同时包含图片与视频，提示并忽略本次结果
      if (result.images.isNotEmpty && result.videos.isNotEmpty) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('只能选择一个视频或9张图片')));
        return;
      }

      setState(() {
        if (result.videos.isNotEmpty) {
          // 如果选择了视频，清空图片列表，只保留视频
          _selectedImages.clear();
          _selectedVideos.clear();
          _selectedVideos.addAll(result.videos);
        } else if (result.images.isNotEmpty) {
          // 如果选择了图片，清空视频列表，添加到图片列表（不超过9张）
          _selectedVideos.clear();
          final remainingSlots = 9 - _selectedImages.length;
          _selectedImages.addAll(result.images.take(remainingSlots));
        }
      });
    }
  }

  /// 删除媒体
  void _removeMedia(int index, {bool isVideo = false}) {
    setState(() {
      if (isVideo) {
        _selectedVideos.removeAt(index);
      } else {
        _selectedImages.removeAt(index);
      }
    });
  }

  /// 提交发帖
  Future<void> _handleSubmit() async {
    // 验证最小提交条件：当没有任何媒体时，content 必填
    final hasAnyMedia =
        _selectedImages.isNotEmpty || _selectedVideos.isNotEmpty;
    if (!hasAnyMedia && _contentController.text.trim().isEmpty) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('请输入分享内容')));
      }
      return;
    }

    // 发布流程：若有媒体，先显示上传进度；媒体全部上传完毕后再进入发布 loading
    // 无媒体则直接进入发布 loading

    try {
      // 先上传媒体到 OSS，获取 ossId 列表
      final ossNotifier = ref.read(ossTokenProvider.notifier);

      List<String?>? imageOssIds;
      List<String?>? videoOssIds;

      final hasAnyMedia =
          _selectedImages.isNotEmpty || _selectedVideos.isNotEmpty;
      final needProgress = hasAnyMedia; // 单张图也显示进度条

      // 使用逐个上传以便展示进度
      setState(() {
        _isUploading = true;
        _uploadTotal = _selectedImages.length + _selectedVideos.length;
        _uploadedCount = 0;
      });

      final List<String?> imgIds = [];
      for (final f in _selectedImages) {
        if (mounted)
          setState(() {
            _currentProgress = 0;
          });
        final id = await ossNotifier.uploadFile(
          f.path,
          source: "topic",
          onProgress: (sent, total) {
            if (!mounted) {
              return;
            }
            setState(() {
              _currentProgress = total == 0 ? 0 : sent / total;
            });
          },
        );
        imgIds.add(id);
        if (mounted) {
          setState(() => _uploadedCount++);
        }
      }
      imageOssIds = imgIds;

      final List<String?> vidIds = [];
      for (final f in _selectedVideos) {
        if (mounted)
          setState(() {
            _currentProgress = 0;
          });
        final id = await ossNotifier.uploadFile(
          f.path,
          source: "topic",
          onProgress: (sent, total) {
            if (!mounted) {
              return;
            }
            setState(() {
              _currentProgress = total == 0 ? 0 : sent / total;
            });
          },
        );
        vidIds.add(id);
        if (mounted) {
          setState(() => _uploadedCount++);
        }
      }
      videoOssIds = vidIds;

      if (mounted) {
        setState(() => _isUploading = false);
      }

      final hasVideo = videoOssIds.whereType<String>().isNotEmpty;
      final hasImage = imageOssIds.whereType<String>().isNotEmpty;
      // mediatype: 0=仅文本, 1=图片+可选文本, 2=视频+可选文本
      final int mediaType = hasVideo ? 2 : (hasImage ? 1 : 0);
      final sid = _selectedCategoryIds.join(',');
      final mediaSrc = hasVideo
          ? videoOssIds.whereType<String>().join(',')
          : (hasImage ? imageOssIds.whereType<String>().join(',') : '');

      // 上传完成，进入发布 loading
      if (mounted)
        setState(() {
          _isSubmitting = true;
        });

      await ref
          .read(lifeRepository)
          .addTopic(
            mediaType: mediaType,
            sid: sid,
            content: _contentController.text.trim(),
            mediaSrc: mediaSrc,
          );

      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });

        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            context.router.maybePop();
          }
        });

        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('帖子审核中，请稍后...')));
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final scaffold = Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black87),
          onPressed: () => context.router.maybePop(),
        ),
        title: const Text('', style: TextStyle(color: Colors.black87)),
        actions: [
          Padding(
            padding: EdgeInsets.only(right: 16.w),
            child: PrimaryButton(
              text: '发布',
              onPressed: _isSubmitting || !_canSubmit ? null : _handleSubmit,
              width: 65.w,
              height: 32.h,
              borderRadius: 4.r,
              padding: EdgeInsets.symmetric(horizontal: 8.w),
              enable: !_isSubmitting && _canSubmit,
              textStyle: context.textTheme.bodyLarge?.copyWith(
                color: Colors.white,
              ),
            ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildMediaSection(),
            SizedBox(height: 16.h),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: ConstrainedBox(
                constraints: BoxConstraints(minHeight: 168.h),
                child: TextField(
                  controller: _contentController,
                  maxLength: 2000,
                  maxLengthEnforcement: MaxLengthEnforcement.enforced,
                  textInputAction: TextInputAction.done,
                  keyboardType: TextInputType.text,
                  onSubmitted: (_) => FocusScope.of(context).unfocus(),
                  onEditingComplete: () => FocusScope.of(context).unfocus(),
                  decoration: InputDecoration(
                    hintText: '写写你分享的内容',
                    hintStyle: context.textTheme.bodyMedium?.copyWith(
                      color: context.customColorThemeNonNull.textColor2,
                    ),
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.zero,
                    counterText: '',
                  ),
                  maxLines: null,
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: context.customColorThemeNonNull.textColor1,
                  ),
                ),
              ),
            ),
            Divider(
              height: 1,
              thickness: 1,
              color:
                  context.customColorThemeNonNull.gray1 ?? Colors.grey.shade200,
            ),
            SizedBox(height: 24.h),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '选择分类',
                    style: context.textTheme.bodyLarge?.copyWith(
                      color: context.customColorThemeNonNull.textColor1,
                    ),
                  ),
                  SizedBox(height: 12.h),
                  Wrap(
                    spacing: 12.w,
                    runSpacing: 12.h,
                    children: _subjects.map((category) {
                      final isSelected = _selectedCategoryIds.contains(
                        category.id,
                      );
                      return _buildCategoryButton(
                        category.name ?? '',
                        isSelected,
                        onTap: () {
                          setState(() {
                            final id = category.id;
                            if (_selectedCategoryIds.contains(id)) {
                              _selectedCategoryIds.remove(id);
                            } else {
                              _selectedCategoryIds.add(id);
                            }
                          });
                        },
                      );
                    }).toList(),
                  ),
                ],
              ),
            ),
            SizedBox(height: 32.h),
          ],
        ),
      ),
    );

    final bool showOverlay = _isSubmitting || _isUploading;
    final Widget? indicator = _isUploading
        ? _buildUploadingIndicator(context)
        : null;

    return FullscreenLoadingOverlay(
      loading: showOverlay,
      indicator: indicator,
      child: scaffold,
    );
  }

  Widget _buildUploadingIndicator(BuildContext context) {
    return Container(
      width: 300.w,
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.15),
            blurRadius: 16,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('图片上传', style: context.textTheme.titleMedium),
              Text(
                '('
                '${_uploadedCount > _uploadTotal ? _uploadTotal : _uploadedCount}'
                '/'
                '$_uploadTotal)',
                style: context.textTheme.bodyMedium,
              ),
            ],
          ),
          SizedBox(height: 12.h),
          ClipRRect(
            borderRadius: BorderRadius.circular(4.r),
            child: LinearProgressIndicator(
              minHeight: 8.h,
              value: _currentProgress,
              backgroundColor:
                  context.customColorThemeNonNull.gray1 ?? Colors.grey.shade200,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建媒体选择区域
  Widget _buildMediaSection() {
    final allMedia = <Widget>[];

    // 添加已选择的图片
    for (int i = 0; i < _selectedImages.length; i++) {
      allMedia.add(
        _buildMediaItem(_selectedImages[i], index: i, isVideo: false),
      );
    }

    // 添加已选择的视频
    for (int i = 0; i < _selectedVideos.length; i++) {
      allMedia.add(
        _buildMediaItem(_selectedVideos[i], index: i, isVideo: true),
      );
    }

    // 添加选择按钮（如果还有空位）
    final bool canAddMore =
        _selectedVideos.isEmpty && _selectedImages.length < 9;
    if (canAddMore) {
      allMedia.add(_buildAddButton());
    }

    if (allMedia.isEmpty) {
      allMedia.add(_buildAddButton());
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Wrap(spacing: 12.w, runSpacing: 12.h, children: allMedia),
    );
  }

  /// 构建媒体项
  Widget _buildMediaItem(
    File file, {
    required int index,
    required bool isVideo,
  }) {
    return FeedbackMediaPreview(
      source: file.path,
      isVideo: isVideo,
      width: 100.w,
      height: 100.w,
      customVideoBuilder: isVideo
          ? (path) => _VideoThumbnail(videoPath: path)
          : null,
      onDelete: () => _removeMedia(index, isVideo: isVideo),
      onTap: (source, isVideoTap) {
        if (isVideoTap) {
          _openVideoPreview(source);
        } else {
          _openImagePreview(index);
        }
      },
    );
  }

  /// 构建添加按钮
  Widget _buildAddButton() {
    return GestureDetector(
      onTap: _pickMedia,
      child: Container(
        width: 100.w,
        height: 100.w,
        decoration: BoxDecoration(
          color: context.customColorThemeNonNull.gray2 ?? Colors.grey.shade100,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color:
                context.customColorThemeNonNull.gray2 ?? Colors.grey.shade300,
            width: 1,
          ),
        ),
        child: Center(
          child: Icon(
            Icons.add,
            size: 32.r,
            color:
                context.customColorThemeNonNull.textColor2 ??
                Colors.grey.shade400,
          ),
        ),
      ),
    );
  }

  /// 构建分类按钮
  Widget _buildCategoryButton(
    String text,
    bool isSelected, {
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        decoration: BoxDecoration(
          color: isSelected
              ? context.colorScheme.primary
              : context.customColorThemeNonNull.gray2 ?? Colors.grey.shade100,
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Text(
          text,
          style: context.textTheme.bodyMedium?.copyWith(
            color: isSelected
                ? Colors.white
                : context.customColorThemeNonNull.textColor1,
          ),
        ),
      ),
    );
  }

  void _openImagePreview(int index) {
    final imageUrls = _selectedImages.map((f) => f.path).toList();
    if (imageUrls.isEmpty) {
      return;
    }
    context.router.push(
      ImageBrowserRoute(imageUrls: imageUrls, initialIndex: index),
    );
  }

  void _openVideoPreview(String source) {
    context.router.push(VideoPlayerRoute(url: source, title: '视频预览'));
  }
}

class _VideoPreviewScreen extends StatelessWidget {
  final VideoSource videoSource;

  const _VideoPreviewScreen({required this.videoSource});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(title: const Text('视频预览'), backgroundColor: Colors.black),
      body: SafeArea(child: VideoPlayerWidget(source: videoSource)),
    );
  }
}

class _VideoThumbnail extends StatefulWidget {
  final String videoPath;

  const _VideoThumbnail({required this.videoPath});

  @override
  State<_VideoThumbnail> createState() => _VideoThumbnailState();
}

class _VideoThumbnailState extends State<_VideoThumbnail> {
  VideoPlayerController? _controller;
  bool _isLoading = true;
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    _loadThumbnail();
  }

  Future<void> _loadThumbnail() async {
    try {
      _controller = VideoPlayerController.file(File(widget.videoPath));
      await _controller!.initialize();
      await _controller!.seekTo(Duration.zero);
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    } catch (_) {
      if (mounted) {
        setState(() {
          _hasError = true;
          _isLoading = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator(strokeWidth: 2));
    }

    if (_hasError || _controller == null || !_controller!.value.isInitialized) {
      return const Center(child: Icon(Icons.videocam, size: 40));
    }

    return FittedBox(
      clipBehavior: Clip.hardEdge,
      fit: BoxFit.cover,
      child: SizedBox(
        width: _controller!.value.size.width,
        height: _controller!.value.size.height,
        child: VideoPlayer(_controller!),
      ),
    );
  }
}
